package com.bjtu;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;

/**
 * @author 周俊宝
 * @date 2022-02-10
 */
public class SshDemo {
    private static final String DEFAULTCHART= "UTF-8";

    /**
     * 连接主机
     * @param url 主机IP
     * @param user 用户名
     * @param password 密码
     * @return 连接主机
     */
    public static Connection getConn(String url,String user,String password){
        Connection conn = new Connection(url);
        try {
            conn.connect();
            if (!"".equals(user) && !"".equals(password)){
                boolean withPassword = conn.authenticateWithPassword(user, password);
                if (!withPassword){
                    throw new IOException("连接失败");
                }
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return conn;
    }

    public static String execute(Connection connection,String shell){
        String result = "";
        try {
            if (connection!=null){
                //打开一个会话
                Session session = connection.openSession();
                //执行命令
                session.execCommand(shell);
                result = processStdout(session.getStdout(), DEFAULTCHART);
                if ("".equals(result)){
                    result = processStdout(session.getStderr(),DEFAULTCHART);
                }
                connection.close();
                session.close();
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return result;
    }
    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


}
